package com.boomshake.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boomshake.dto.StoreCreateDTO;
import com.boomshake.dto.StoreUpdateDTO;
import com.boomshake.entity.Store;
import com.boomshake.mapper.StoreMapper;
import com.boomshake.service.StoreService;
import com.boomshake.vo.StoreVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 门店服务实现类
 *
 * @author BoomShake
 * @date 2024-12-15
 */
@Service
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {

    @Resource
    private StoreMapper storeMapper;

    @Override
    public IPage<StoreVO> getStoreList(Integer page, Integer size, String name, Integer status) {
        Page<Store> storePage = new Page<>(page, size);
        IPage<Store> storeIPage = storeMapper.selectStorePage(storePage, name, status);
        
        // 转换为VO
        IPage<StoreVO> voPage = new Page<>(page, size, storeIPage.getTotal());
        List<StoreVO> voList = storeIPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        voPage.setRecords(voList);
        
        return voPage;
    }

    @Override
    public StoreVO getStoreById(Long id) {
        Store store = this.getById(id);
        return store != null ? convertToVO(store) : null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StoreVO createStore(StoreCreateDTO createDTO) {
        // 检查门店编码是否已存在
        if (checkCodeExists(createDTO.getCode(), null)) {
            throw new RuntimeException("门店编码已存在");
        }

        Store store = new Store();
        BeanUtils.copyProperties(createDTO, store);
        
        if (this.save(store)) {
            return convertToVO(store);
        }
        throw new RuntimeException("创建门店失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StoreVO updateStore(StoreUpdateDTO updateDTO) {
        Store existingStore = this.getById(updateDTO.getId());
        if (existingStore == null) {
            throw new RuntimeException("门店不存在");
        }

        // 检查门店编码是否重复（排除自己）
        if (StringUtils.hasText(updateDTO.getName()) && 
            !existingStore.getName().equals(updateDTO.getName())) {
            // 只有当名称确实发生变化时才进行检查
        }

        // 只更新非空字段
        if (StringUtils.hasText(updateDTO.getName())) {
            existingStore.setName(updateDTO.getName());
        }
        if (StringUtils.hasText(updateDTO.getAddress())) {
            existingStore.setAddress(updateDTO.getAddress());
        }
        if (StringUtils.hasText(updateDTO.getPhone())) {
            existingStore.setPhone(updateDTO.getPhone());
        }
        if (StringUtils.hasText(updateDTO.getBusinessHours())) {
            existingStore.setBusinessHours(updateDTO.getBusinessHours());
        }
        if (updateDTO.getStatus() != null) {
            existingStore.setStatus(updateDTO.getStatus());
        }
        if (updateDTO.getDescription() != null) {
            existingStore.setDescription(updateDTO.getDescription());
        }
        if (updateDTO.getImages() != null) {
            existingStore.setImages(updateDTO.getImages());
        }

        if (this.updateById(existingStore)) {
            return convertToVO(existingStore);
        }
        throw new RuntimeException("更新门店失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteStore(Long id) {
        Store store = this.getById(id);
        if (store == null) {
            throw new RuntimeException("门店不存在");
        }
        
        // TODO: 检查门店是否有关联的数据（如分销员、订单等）
        // 这里可以添加业务校验逻辑
        
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStoreStatus(Long id, Integer status) {
        Store store = this.getById(id);
        if (store == null) {
            throw new RuntimeException("门店不存在");
        }

        store.setStatus(status);
        return this.updateById(store);
    }

    @Override
    public List<StoreVO> getActiveStores() {
        List<Store> activeStores = storeMapper.selectActiveStores();
        return activeStores.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public Map<String, Object> getStoreStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 总门店数
        long totalCount = this.count();
        statistics.put("totalCount", totalCount);
        
        // 各状态门店数量
        List<StoreMapper.StoreStatusCount> statusCounts = storeMapper.selectStatusStatistics();
        Map<String, Integer> statusStatistics = new HashMap<>();
        statusStatistics.put("active", 0);    // 营业中
        statusStatistics.put("paused", 0);    // 暂停营业
        statusStatistics.put("closed", 0);    // 已关闭
        
        for (StoreMapper.StoreStatusCount statusCount : statusCounts) {
            switch (statusCount.getStatus()) {
                case 1:
                    statusStatistics.put("active", statusCount.getCount());
                    break;
                case 2:
                    statusStatistics.put("paused", statusCount.getCount());
                    break;
                case 3:
                    statusStatistics.put("closed", statusCount.getCount());
                    break;
            }
        }
        statistics.put("statusStatistics", statusStatistics);
        
        return statistics;
    }

    @Override
    public boolean checkCodeExists(String code, Long excludeId) {
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        if (excludeId != null) {
            queryWrapper.ne("id", excludeId);
        }
        return this.count(queryWrapper) > 0;
    }

    /**
     * 将Store实体转换为StoreVO
     */
    private StoreVO convertToVO(Store store) {
        StoreVO vo = new StoreVO();
        BeanUtils.copyProperties(store, vo);
        vo.setStatusText(); // 设置状态文本
        return vo;
    }
} 